package com.ls.mysql.controller;


import com.alibaba.fastjson.JSONObject;
import com.ls.mysql.util.JWTUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author Maple.Chen
 * @Description 测试使用token令牌验证机制
 * TOOLs: TestController、JWTUtil、CToken
 * @Date 9:48 2020/5/27
 **/
@RestController
public class TestController {

    /*
        模拟登陆成功发放带有时效的token令牌
     */
    @RequestMapping(value = "test/login", method = RequestMethod.POST)
    public JSONObject login(HttpServletResponse response) {
        JSONObject json = new JSONObject();
        json.put("statusCode", 1);
        json.put("msg", "登陆成功，发放token令牌");
        /*
        令牌附加信息，Claim
         */
        String tokenCode = JWTUtil.sign("zhangsan6599", "7ef8659r");
        response.setHeader("userToken", tokenCode);
        json.put("狗头打印令牌id", tokenCode);
        return json;
    }

    /*
        模拟客户端请求使用令牌来完成接口请求
        并打印该token
     */
    @RequestMapping(value = "test/print", method = RequestMethod.POST)
    public JSONObject verify(HttpServletRequest request) {
        JSONObject json = new JSONObject();
        String token = request.getHeader("userToken");
        /*
        由于拦截器已经验证过了，所以能到达此处的请求必须是已经通过验证的
         */
        json.put("statusCode", 1);
        json.put("msg", "验证成功，有效的token令牌");
        json.put("狗头打印令牌id", token);
        json.put("登陆用户的用户名", JWTUtil.getClaim(token, "loginName"));
        return json;
    }

}
